import { ValidateByOptions } from './../node_modules/class-validator/types/decorator/common/ValidateBy.d';
import { VersioningType } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { Request, Response } from 'express';
import * as session from 'express-session'
import { NestExpressApplication } from '@nestjs/platform-express';
import { join } from 'path';
import * as cors from 'cors';
import { ResponseInterceptor } from './common/response';
import { HttpFilter } from './common/filter';
import { ValidationPipe } from '@nestjs/common';
import { RolesGuard } from './guard/roles.guard';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';

// 2、 中间件之全局中间件
// 注意全局中间件只能使用函数模式 案例可以做白名单拦截之类的
let whiteList = ['/list', '/list/one']
function middleWareAll(req: Request, res: Response, next: (error?: any) => void) {
  console.log('我是全局中间件:', req.method, req.originalUrl);
  if (whiteList.includes(req.originalUrl)) {
    next()
  } else {
    res.send({
      code: 1001,
      msg: '该路由不在白名单内,禁止访问'
    })
  }
}

async function bootstrap() {
  const app = await NestFactory.create<NestExpressApplication>(AppModule);
  // 生成静态目录访问上传之后的图片 useStaticAssets prefix 是虚拟前缀
  // app.useStaticAssets(join(__dirname, './public/uploadimgs'),{
  //     prefix: "/uploadimgs"
  // })
  app.useStaticAssets(join(__dirname, './public'), {
    prefix: "/public"
  });
  
  // 开启URI上的版本控制
  app.enableVersioning({
    type: VersioningType.URI,
  });

  // 使用session插件
  app.use(session({ secret: "mingle", name: "ml.session", rolling: true, cookie: { maxAge: null } }));

  // 使用全局中间件
  // app.use(middleWareAll);

  // 3.中间件之接入第三方中间件 例如 cors 处理跨域
  // npm install cors
  // npm install @types/cors -D
  app.use(cors())

  // 注册响应拦截器
  app.useGlobalInterceptors(new ResponseInterceptor());
  // 响应错误拦截器
  app.useGlobalFilters(new HttpFilter())

  // 注册全局DTO验证管道 
  // app.useGlobalPipes(new ValidationPipe())

  // 注册全局守卫
  // app.useGlobalGuards(new RolesGuard())

  // 注册swagger文档插件
  const options = new DocumentBuilder().setTitle('mingle接口文档').setDescription('给予nestjs的借口文档').setVersion('1').build();
  const document = SwaggerModule.createDocument(app, options)
  SwaggerModule.setup('/api-docs', app, document);

  await app.listen(3001);
}
bootstrap();
